package com.mingqijia.gassafety.webserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gap.basic.exception.BizException;
import com.mingqijia.gassafety.authority.api.web.facade.DictionaryManageFacade;
import com.mingqijia.gassafety.db.entity.AicallTask;
import com.mingqijia.gassafety.db.entity.BusinessNotice;
import com.mingqijia.gassafety.db.entity.BusinessNoticeTemplate;
import com.mingqijia.gassafety.db.entity.Dictionary;
import com.mingqijia.gassafety.db.mapper.BusinessNoticeMapper;
import com.mingqijia.gassafety.db.mapper.DictionaryMapper;
import com.mingqijia.gassafety.shared.constant.*;
import com.mingqijia.gassafety.shared.dto.LogVO;
import com.mingqijia.gassafety.shared.enums.YesNoEnum;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.request.BrowserNotifyReason;
import com.mingqijia.gassafety.webserver.request.BusinessNoticeRequest;
import com.mingqijia.gassafety.webserver.request.EquipmentPeriodRequest;
import com.mingqijia.gassafety.webserver.response.BusinessNoticeResponse;
import com.mingqijia.gassafety.webserver.service.AicallTaskService;
import com.mingqijia.gassafety.webserver.service.BusinessNoticeService;
import com.mingqijia.gassafety.webserver.service.BusinessNoticeTemplateService;
import com.mingqijia.gassafety.webserver.service.EquipmentManufacturerService;
import com.mingqijia.gassafety.webserver.utils.LogRecordAspect;
import com.mingqijia.gassafety.webserver.utils.LogUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;

import static com.mingqijia.gassafety.webserver.service.impl.WarningDataServiceImpl.split_f;

/**
 * <p>
 * 业务通知规则表 服务实现类
 * </p>
 *
 * @author wanghai
 * @since 2022-04-28
 */
@Service
@Slf4j
public class BusinessNoticeServiceImpl extends ServiceImpl<BusinessNoticeMapper, BusinessNotice> implements BusinessNoticeService {

    private static final String phoneRegex = "^(1[3-9])\\d{9}$";
    private static final String landlineRegex = "\\d{3,4}[-]\\d{7,8}";

    @Value(value = "${gassafety.xf.call.robotId}")
    public String robotId;

    @Autowired
    BusinessNoticeTemplateService businessNoticeTemplateService;

    @Autowired
    AicallTaskService aicallTaskService;

    @Autowired
    DictionaryMapper dictionaryMapper;

    @Autowired
    DictionaryManageFacade dictionaryManageFacade;


    @Autowired
    EquipmentManufacturerService equipmentManufacturerService;
    @Override
    public PageUtil<BusinessNoticeResponse> getList(String paramName, String paramCode, Integer page, Integer pageSize) {
        List<BusinessNoticeResponse> resultList = new ArrayList<>();
        String spId = ApplicationUtils.getWorkingSpId();
        Map<String, Object> pMap = new HashMap<>();
        pMap.put("paramName",paramName);
        pMap.put("paramCode",paramCode);
        pMap.put("spId",spId);

        int total = baseMapper.selectCountTotal(pMap);

        int start = (page - 1) * pageSize;
        pMap.put("start",start);
        pMap.put("pageSize",pageSize);
        List<Map<String, Object>> list = baseMapper.getList(pMap);
        Map<String, String> hashMap = EquipmentManufacturerMap();
        for (Map<String,Object> item : list) {
            BusinessNoticeResponse res = new BusinessNoticeResponse();
            BeanUtil.copyProperties(item, res);
            if(!StringUtils.isEmpty(res.getRobotContent())){
                String robotContent = res.getRobotContent();
                for(String key:Constants.ROBOT_CONTENT_KEY_MAP.keySet()){
                    robotContent = robotContent.replace(Constants.ROBOT_CONTENT_KEY_MAP.get(key),key);
                }
                res.setRobotContent(robotContent);
            }
            if (res.getParamCode().equals("system_pop_presentation_format")){
                QueryWrapper<BusinessNotice> businessNoticeQueryWrapper = new QueryWrapper<>();
                businessNoticeQueryWrapper.lambda().eq(BusinessNotice::getIsDeleted, 0)
                        .eq(BusinessNotice::getParamCode, res.getParamCode()).eq(BusinessNotice::getSpId, spId);

                BusinessNotice businessNotice = baseMapper.selectOne(businessNoticeQueryWrapper);
                if (businessNotice != null){
                    res.setPopMinutes(businessNotice.getPopMinutes());
                    res.setPopSeconds(businessNotice.getPopSeconds());
                }
            }
            // 由于数据存储方式不同，需要特殊处理
            if (res.getParamCode().equals("device_offline_automation")) {
                QueryWrapper<BusinessNotice> businessNoticeQueryWrapper = new QueryWrapper<>();
                businessNoticeQueryWrapper.lambda().eq(BusinessNotice::getIsDeleted, 0)
                        .eq(BusinessNotice::getParamCode, res.getParamCode()).eq(BusinessNotice::getSpId, spId);

                BusinessNotice businessNotice = baseMapper.selectOne(businessNoticeQueryWrapper);
                if (businessNotice != null ){
                    res.setSetRange(Integer.parseInt(businessNotice.getSetRange()));
                    res.setIsNotice(businessNotice.getIsNotice() == 1);
                    ArrayList<EquipmentPeriodRequest> equipmentPeriodRequests = new ArrayList<>();
                    if (businessNotice.getSetRange().equals("2")) {
                        log.info("businessNotice:{}", businessNotice);
                        List<String> EquipmentTypes = new ArrayList<>();
                        List<String> Period = new ArrayList<>();
                        if (businessNotice.getEquipmentType().contains(";")){
                            EquipmentTypes = Arrays.asList(businessNotice.getEquipmentType().split(";"));
                            Period = Arrays.asList(businessNotice.getPeriod().split(";"));
                        }else {
                            EquipmentTypes.add(businessNotice.getEquipmentType());
                            Period.add(businessNotice.getPeriod());
                        }
                        for (int i = 0; i < Period.size(); i++) {
                            EquipmentPeriodRequest equipmentPeriodRequest = new EquipmentPeriodRequest();
                            equipmentPeriodRequest.setPeriod(Period.get(i));
                            equipmentPeriodRequest.setEquipmentType(EquipmentTypes.get(i));
                            equipmentPeriodRequests.add(equipmentPeriodRequest);
                        }
                        res.setEquipmentPeriod(equipmentPeriodRequests);
                    } else if (businessNotice.getSetRange().equals("3")) {
                        List<String> EquipmentManufacturers = new ArrayList<>();
                        List<String> EquipmentModels = new ArrayList<>();
                        List<String> Period = new ArrayList<>();

                        if (businessNotice.getPeriod().contains(";")){
                            EquipmentManufacturers = Arrays.asList(businessNotice.getEquipmentManufacturer().split(";"));
                            EquipmentModels = Arrays.asList(businessNotice.getEquipmentModel().split(";"));
                            Period = Arrays.asList(businessNotice.getPeriod().split(";"));
                        }else {
                            EquipmentManufacturers.add(businessNotice.getEquipmentManufacturer());
                            EquipmentModels.add(businessNotice.getEquipmentModel());
                            Period.add(businessNotice.getPeriod());
                        }
                        for (int i = 0; i < Period.size(); i++) {
                            EquipmentPeriodRequest equipmentPeriodRequest = new EquipmentPeriodRequest();
                            equipmentPeriodRequest.setPeriod(Period.get(i));
                            equipmentPeriodRequest.setEquipmentModel(EquipmentModels.get(i));
                            equipmentPeriodRequest.setEquipmentManufacturer(EquipmentManufacturers.get(i));
                            equipmentPeriodRequest.setEquipmentManufacturerStr(hashMap.get(EquipmentManufacturers.get(i)));
                            equipmentPeriodRequests.add(equipmentPeriodRequest);
                        }
                        res.setEquipmentPeriod(equipmentPeriodRequests);
                    }else {
                        res.setPeriod(businessNotice.getPeriod());
                    }
                }

            }

            if (isSystemUntreated(res.getParamCode())){
                QueryWrapper<BusinessNotice> businessNoticeQueryWrapper = new QueryWrapper<>();
                businessNoticeQueryWrapper.lambda().eq(BusinessNotice::getIsDeleted, 0)
                        .eq(BusinessNotice::getParamCode, res.getParamCode()).eq(BusinessNotice::getSpId, spId);

                BusinessNotice businessNotice = baseMapper.selectOne(businessNoticeQueryWrapper);
                if (businessNotice != null){
                    res.setSetRadius(businessNotice.getSetRange());
                    res.setPopMinutes(businessNotice.getPopMinutes());
                    res.setPopSeconds(businessNotice.getPopSeconds());
                } else {
                    res.setParamValue("OFF");
                    res.setSetRadius("1,2");
                    res.setPopMinutes(0);
                    res.setPopSeconds(10);
                }
            }
            resultList.add(res);
        }
        PageUtil<BusinessNoticeResponse> pageInfo = new PageUtil<>(page, pageSize, total, resultList);
        log.info("业务通知列表：" + resultList.toString());
        return pageInfo;
    }

    @Override
    public void create(BusinessNoticeRequest req) {
        BusinessNoticeTemplate template = businessNoticeTemplateService.getTemplateParam(req.getParamCode());

        //企业级操作日志
        LogVO vo = new LogVO();
        vo = formatLog( vo, template, req.getParamValue() );
        vo.setDetail(vo.getDetail()+"失败");
        vo.setCommonInfo(template.getParamName());
        LogRecordAspect.threadLocal.set(vo);

        if (template.getParamType() == 1) { //开关
            if (StringUtils.isEmpty(req.getParamValue())) {//参数值没设置
                throw new BizException("参数值不能为空！");
            }
            if ( !GssBusinessNoticeConstant.TEMPLATE_SWITCH_VALUES.contains(req.getParamValue()) ){//参数值验证
                throw new BizException("开关的参数值仅能是ON,OFF");
            }
        }

        String spId = ApplicationUtils.getWorkingSpId();
        LambdaQueryWrapper<BusinessNotice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusinessNotice::getParamCode, req.getParamCode())
                .eq(BusinessNotice::getIsDeleted, 0)
                .eq(BusinessNotice::getSpId, spId);
        int count = this.count(queryWrapper);
        if (count > 0) {
            throw new BizException("业务通知已存在");
        }
        BusinessNotice notice = new BusinessNotice();
        notice.setParamName(template.getParamName());
        notice.setParamValue(req.getParamValue());
        notice.setParamCode(req.getParamCode());
        notice.setRemark(template.getRemark());
        notice.setSpId(spId);

        String aicallTaskLog = "";
        if (isFristBrokenNotice(req.getParamCode())) {
            //设备故障首次提醒
            if (StringUtils.isEmpty(req.getPushPhones()) &&
                    StringUtils.isEmpty(req.getPushLevel()) &&
                    StringUtils.isEmpty(req.getPushStaffs()))
                throw new BizException("请输入至少一种联系方式");
            String callPhones = "";
            String pushStaffs = "";
            callPhones = req.getPushPhones();
            pushStaffs = req.getPushStaffs();
            if (!StringUtils.isEmpty(callPhones)) {
                if (!callPhones.contains(split_f)) callPhones = callPhones + ";";
                checkPhone(callPhones);
                notice.setPushPhones(callPhones);
            }
            if (!StringUtils.isEmpty(pushStaffs)) {
                if (!pushStaffs.contains(split_f)) pushStaffs = pushStaffs + ";";
                checkPhone(pushStaffs);
                notice.setPushStaffs(pushStaffs);
            }
            notice.setPushLevel(req.getPushLevel());
        }else if( isAiCallParamCode(req.getParamCode()) ){
            boolean f = checkAiCallParam(req);
            AicallTask aicallTask = new AicallTask();
            aicallTask.setAppKey(req.getAppKey());
            aicallTask.setAppSecret(req.getAppSecret());
            aicallTask.setRobotId(req.getRobotId());
            aicallTask.setLineNum(req.getLineNum());
            aicallTask.setRobotContent(req.getRobotContent());
            notice.setParamValue(GssBusinessNoticeConstant.TEMPLATE_SWITCH_ON);
            if( f ){
                handleAiCallParam(req, spId);
            }
            aicallTaskLog = LogUtil.addOrDeleteEntity(aicallTask, AicallTask.class);
        } else if (isDeviceOfflineAutomation(req.getParamCode())) {
            if (req.getSetRange() <= 0) {
                throw new BizException("请选择一种设置范围");
            }
            // 不同的范围进行走不同逻辑
            if (req.getSetRange() == 1) {
                notice.setSetRange("1");
                if (StringUtils.isEmpty(req.getPeriod()) || Integer.parseInt(req.getPeriod()) <= 0) {
                    throw new BizException("周期设置必须大于0");
                }else {
                    notice.setPeriod(req.getPeriod());
                }
                notice.setIsNotice(req.getIsNotice() ? 1 : 0); //离线情况是否通知 true-1、false-0
                notice.setEquipmentManufacturer("");
                notice.setEquipmentModel("");
                notice.setEquipmentType("");
            } else if (req.getSetRange() == 2) {
                notice.setSetRange("2");
                notice.setIsNotice(req.getIsNotice() ? 1 : 0); //离线情况是否通知 true-1、false-0
                if (!CollectionUtils.isEmpty(req.getEquipmentPeriod())) {
                    StringBuilder period = new StringBuilder();
                    StringBuilder equipmentType = new StringBuilder();
                    for (int i = 0; i < req.getEquipmentPeriod().size(); i++) {
                        if (i != 0) {
                            period.append(";");
                            equipmentType.append(";");
                        }
                        if (StringUtils.isEmpty(req.getEquipmentPeriod().get(i).getPeriod()) || Integer.parseInt(req.getEquipmentPeriod().get(i).getPeriod()) <= 0) {
                            throw new BizException("周期设置必须大于0");
                        }else {
                            period.append(req.getEquipmentPeriod().get(i).getPeriod());
                        }
                        equipmentType.append(req.getEquipmentPeriod().get(i).getEquipmentType());
                    }
                    notice.setPeriod(period.toString());
                    notice.setEquipmentType(equipmentType.toString());
                    notice.setEquipmentModel("");
                    notice.setEquipmentManufacturer("");
                }
            } else {
                notice.setSetRange("3");
                notice.setIsNotice(req.getIsNotice() ? 1 : 0); //离线情况是否通知 true-1、false-0
                if (!CollectionUtils.isEmpty(req.getEquipmentPeriod())) {
                    StringBuilder period = new StringBuilder();
                    StringBuilder equipmentManufacturer = new StringBuilder();
                    StringBuilder equipmentModel = new StringBuilder();
                    for (int i = 0; i < req.getEquipmentPeriod().size(); i++) {
                        if (i != 0) {
                            period.append(";");
                            equipmentManufacturer.append(";");
                            equipmentModel.append(";");
                        }
                        if (StringUtils.isEmpty(req.getEquipmentPeriod().get(i).getPeriod()) || Integer.parseInt(req.getEquipmentPeriod().get(i).getPeriod()) <= 0) {
                            throw new BizException("周期设置必须大于0");
                        }else {
                            period.append(req.getEquipmentPeriod().get(i).getPeriod());
                        }
                        equipmentManufacturer.append(req.getEquipmentPeriod().get(i).getEquipmentManufacturer());
                        equipmentModel.append(req.getEquipmentPeriod().get(i).getEquipmentModel());
                    }
                    notice.setPeriod(period.toString());
                    notice.setEquipmentManufacturer(equipmentManufacturer.toString());
                    notice.setEquipmentModel(equipmentModel.toString());
                    notice.setEquipmentType("");
                }
            }
        }
        if (isSystemUntreated(req.getParamCode())) {
            if (StringUtils.isEmpty(req.getParamValue())) {//参数值没设置
                throw new BizException("参数值不能为空！");
            }
            if ("OFF".equals(req.getParamValue())) {
                if (StringUtils.isEmpty(req.getSetRadius())) {
                    throw new BizException("请选择一种设置范围");
                }
                Integer popMinutes = req.getPopMinutes();
                if (popMinutes == null) {
                    popMinutes = 0;
                }
                Integer popSeconds = req.getPopSeconds();
                if (popSeconds == null) {
                    popSeconds = 0;
                }
                if (popMinutes <= 0 && popSeconds <= 0) {
                    throw new BizException("请选择一种自动时间");
                }
                if (popSeconds <= 0 && popMinutes > 0 && popMinutes < 5) {
                    throw new BizException("需要有最小值，如5");
                }
            }
            if ("ON".equals(req.getParamValue())) {
                if (StringUtils.isEmpty(req.getSetRadius())) {
                    throw new BizException("请选择一种设置范围");
                }
            }
            notice.setSetRange(req.getSetRadius());
            notice.setPopMinutes(req.getPopMinutes());
            notice.setPopSeconds(req.getPopSeconds());
        }
        if (isSystemPopPresentationFormat(req.getParamCode())){
            notice.setPopMinutes(req.getPopMinutes());
            notice.setPopSeconds(req.getPopSeconds());
        }

        log.info("新增业务通知：" + notice.toString());
        this.save(notice);

        Map<String, String> hashMap = EquipmentManufacturerMap();
        //企业级操作日志
        LogVO vo2 = new LogVO();
        vo2 = formatLog( vo2, template, req.getParamValue() );
        if( isIgnoreParamValue(req.getParamCode()) ){
            notice.setParamValue(null);
        }
        // 特殊处理字段
        if (isDeviceOfflineAutomation(req.getParamCode())){
            if (notice.getSetRange().equals("1")){
                notice.setSetRange("所有设备");
            }else if (notice.getSetRange().equals("2")){
                notice.setSetRange("设备类型");
            }else if (notice.getSetRange().equals("3")){
                notice.setSetRange("设备型号");
            }
            if (!StringUtils.isEmpty(notice.getEquipmentType())){
                if (notice.getEquipmentType().contains(";")){
                    List<String> split = Arrays.asList(notice.getEquipmentType().split(";"));
                    StringBuilder equipmentType = new StringBuilder();
                    for (int i = 0; i < split.size(); i++) {
                        if (i != 0) {
                            equipmentType.append(";");
                        }
                        equipmentType.append(EquipmentType.parse(split.get(i)).getName());
                    }
                    notice.setEquipmentType(equipmentType.toString());
                }else {
                    notice.setEquipmentType(EquipmentType.parse(notice.getEquipmentType()).getName());
                }
            }
            if (!StringUtils.isEmpty(notice.getEquipmentManufacturer()) ){
                System.out.println("进入设备厂商判断");
                if (notice.getEquipmentManufacturer().contains(";")){
                    List<String> split = Arrays.asList(notice.getEquipmentManufacturer().split(";"));
                    StringBuilder equipmentManufacturer = new StringBuilder();
                    for (int i = 0; i < split.size(); i++) {
                        if (i != 0) {
                            equipmentManufacturer.append(";");
                        }
                        equipmentManufacturer.append(hashMap.get(split.get(i)));
                    }
                    notice.setEquipmentManufacturer(equipmentManufacturer.toString());
                }else {
                    notice.setEquipmentManufacturer(hashMap.get(notice.getEquipmentManufacturer()));
                }
            }
        }
        if (isSystemPopPresentationFormat(req.getParamCode())){
            if (req.getParamValue().equals("OFF")){
                notice.setParamValue("自动关闭");
            }else {
                notice.setParamValue("手动关闭");
            }
        }
        if (isSystemUntreated(req.getParamCode())){
            if (req.getParamValue().equals("OFF")){
                notice.setParamValue("自动关闭");
            }else if (req.getParamValue().equals("ON")){
                notice.setParamValue("手动关闭");
            } else {
                notice.setParamValue("不提醒");
            }
            String setRange = req.getSetRadius();
            String[] split = setRange.split(",");
            StringBuilder sb = new StringBuilder();
            for (String rane : split) {
                if (rane.equals("1")) {
                    sb.append("报警记录未处理提醒,");
                }else if (rane.equals("2")){
                    sb.append("故障记录未处理提醒,");
                }
            }
            if (sb.length() > 0) {
                notice.setSetRange(sb.toString().substring(0, sb.length() - 1));
            } else {
                notice.setSetRange("");
            }
        }
        vo2.setDetail(vo2.getDetail() + "成功\n" +
                LogUtil.addOrDeleteEntity(notice, BusinessNotice.class) + "\n" + aicallTaskLog);
        vo2.setCommonInfo(notice.getParamName());
        LogRecordAspect.threadLocal.set(vo2);
    }

    private boolean isFristBrokenNotice(String paramCode) {
        if (BusinessNoticeParam.BROKEN_FIRST_TIME_MSG.getCode().equals(paramCode) ||
                BusinessNoticeParam.BROKEN_FIRST_TIME_WECHAT.getCode().equals(paramCode)) {
            return true;
        }
        return false;
    }

    private boolean isSystemPopPresentationFormat(String paramCode) {
        if (BusinessNoticeParam.SYSTEM_POP_PRESENTATION_FORMAT.getCode().equals(paramCode)) {
            return true;
        }
        return false;
    }

    private boolean isDeviceOfflineAutomation(String paramCode) {
        return BusinessNoticeParam.DEVICE_OFFLINE_AUTOMATION.getCode().equals(paramCode);
    }

    private boolean isSystemUntreated(String paramCode) {
        return BusinessNoticeParam.SYSTEM_ALERT_POP_SETTINGS.getCode().equals(paramCode);
    }

    private void checkPhone(String highWxPhones) {
        String[] split = highWxPhones.split(WarnStrategyServiceImpl.split);
        for (String s : split) {
            boolean isMatch = Pattern.matches(phoneRegex, s);
            boolean landlineMatch = Pattern.matches(landlineRegex, s);
            if (!isMatch && !landlineMatch) throw new BizException("联系方式格式存在错误");
        }
    }

    /**
     * 是否外呼参数code
     * @param paramCode
     * @return
     */
    private boolean isAiCallParamCode(String paramCode){
        return GssBusinessNoticeConstant.AICALL_PARAM_CODES.contains(paramCode);
    }

    /**
     * 处理外呼参数
     * @param req
     * @throws BizException
     */
    private void handleAiCallParam(BusinessNoticeRequest req,String spId) throws BizException{
        aicallTaskService.handleAicallTask(req,spId);
    }
    /**
     * 校验外呼参数是否都配置
     *
     * @param req
     * @return
     * @throws BizException
     */
    private boolean checkAiCallParam(BusinessNoticeRequest req) throws BizException{
        int i = 0;
        if( !StringUtils.isEmpty(req.getAppKey()) ){
            i++;
        }
        if( !StringUtils.isEmpty(req.getAppSecret() ) ){
            i++;
        }
        if( !StringUtils.isEmpty(req.getRobotId() ) ){
            i++;
        }
        if( !StringUtils.isEmpty(req.getLineNum() ) ){
            i++;
        }
        if( i>0 && i!=4 ){
            throw new BizException("外呼配置【appKey,appSecret,话术,线路,音色】必须同时都配置，缺一不可");
        }
        return i==4;
    }

    /**
     * 是否忽略param_value的值
     * @param paramCode
     * @return
     */
    private boolean isIgnoreParamValue(String paramCode){
        return "cockpit_title".equals(paramCode) || "cm_service_hot_line".equals(paramCode) || "broken_first_time_wechat".equals(paramCode)
                || "broken_first_time_msg".equals(paramCode) || "system_pop_presentation_format".equals(paramCode) || "industry_screen_title".equals(paramCode) || "system_alert_pop_settings".equals(paramCode) ? false : true;
    }

    /**
     * 处理日志
     * @param vo
     * @param template
     * @param paramValue
     * @return
     */
    private LogVO formatLog(LogVO vo, BusinessNoticeTemplate template, String paramValue ){
        if( GssBusinessNoticeConstant.TEMPLATE_SWITCH.equals(template.getParamType()) ){//开关
            vo.setOperateRecordEnum( GssBusinessNoticeConstant.TEMPLATE_SWITCH_ON.equals(paramValue) ?
                    OperateRecordEnum.OPERATE_TYPE_57 : OperateRecordEnum.OPERATE_TYPE_58 );
            vo.setDetail("【"+template.getParamName()+"】");
        }else if( GssBusinessNoticeConstant.TEMPLATE_CONFIG.equals(template.getParamType()) ){//参数配置
            vo.setOperateRecordEnum(OperateRecordEnum.OPERATE_TYPE_59);
            vo.setDetail("【"+template.getParamName()+"】参数值");
        }
        return vo;
    }

    @Override
    public BusinessNoticeResponse detail(Map<String, String> req) {
        String spId = ApplicationUtils.getWorkingSpId();
        Map<String, Object> pMap = new HashMap<>();
        pMap.put("spId",spId);
        if( !ObjectUtils.isEmpty(req.get("id")) ){
            pMap.put("id",req.get("id"));
        }else if( !StringUtils.isEmpty(req.get("paramCode")) ){
            pMap.put("paramCode",req.get("paramCode"));
        }else{
            return null;
        }
        List<Map<String, Object>> list = baseMapper.getList(pMap);
        if( ObjectUtils.isEmpty(list) ){
            return null;
        }
        BusinessNoticeResponse businessNoticeResponse = new BusinessNoticeResponse();
        BeanUtil.copyProperties(list.get(0),businessNoticeResponse);
        if( isAiCallParamCode(businessNoticeResponse.getParamCode()) ){
            if( StringUtils.isEmpty(businessNoticeResponse.getRobotId()) ){
                businessNoticeResponse.setRobotId(robotId);
            }
            if( StringUtils.isEmpty(businessNoticeResponse.getLineNum()) ){
                businessNoticeResponse.setLineNum("65008475");
            }
            if( StringUtils.isEmpty(businessNoticeResponse.getVoiceCode()) ){
                businessNoticeResponse.setVoiceCode("62360");
            }
        }
        return businessNoticeResponse;
    }

    @Override
    public void edit(BusinessNoticeRequest req, String spId,BusinessNotice businessNotice) {
        BusinessNoticeTemplate template = businessNoticeTemplateService.getTemplateParam(req.getParamCode());

        //企业级操作日志
        LogVO vo = new LogVO();
        vo = formatLog( vo, template, req.getParamValue() );
        vo.setDetail(vo.getDetail() + "失败");
        vo.setCommonInfo(businessNotice.getParamName());
        LogRecordAspect.threadLocal.set(vo);

        if (template.getParamType() == 1) { //开关
            if (StringUtils.isEmpty(req.getParamValue())) {//参数值没设置
                throw new BizException("参数值不能为空！");
            }
            if ( !GssBusinessNoticeConstant.TEMPLATE_SWITCH_VALUES.contains(req.getParamValue()) ){//参数值验证
                throw new BizException("开关的参数值仅能是ON,OFF");
            }
        }

        BusinessNotice notice = new BusinessNotice();
        notice.setId(req.getId());
        notice.setParamCode(req.getParamCode());
        notice.setParamName(template.getParamName());
        notice.setParamValue(req.getParamValue());
        notice.setRemark(template.getRemark());
        notice.setSpId(spId);

        AicallTask oldAicallTask = new AicallTask();
        AicallTask aicallTask = new AicallTask();

        if (isFristBrokenNotice(req.getParamCode())) {
            //设备故障首次提醒
            if (StringUtils.isEmpty(req.getPushPhones()) &&
                    StringUtils.isEmpty(req.getPushLevel()) &&
                    StringUtils.isEmpty(req.getPushStaffs()))
                throw new BizException("请输入至少一种联系方式");
            String callPhones = "";
            String pushStaffs = "";
            callPhones = req.getPushPhones();
            pushStaffs = req.getPushStaffs();
            if (!StringUtils.isEmpty(callPhones)) {
                if (!callPhones.contains(split_f)) callPhones = callPhones + ";";
                checkPhone(callPhones);
                notice.setPushPhones(callPhones);
            }
            if (!StringUtils.isEmpty(pushStaffs)) {
                if (!pushStaffs.contains(split_f)) pushStaffs = pushStaffs + ";";
                checkPhone(pushStaffs);
                notice.setPushStaffs(pushStaffs);
            }
            notice.setPushLevel(req.getPushLevel());
        }else if( isAiCallParamCode(req.getParamCode()) ){
            boolean f = checkAiCallParam(req);
            oldAicallTask = getOldAiCallTask(spId,req.getParamCode());
            BeanUtil.copyProperties(oldAicallTask,aicallTask);
            if( f || !StringUtils.isEmpty(req.getRobotContent()) ){
                aicallTask.setAppKey(req.getAppKey());
                aicallTask.setAppSecret(req.getAppSecret());
                aicallTask.setRobotId(req.getRobotId());
                aicallTask.setLineNum(req.getLineNum());
                aicallTask.setRobotContent(StringUtils.isEmpty(req.getRobotContent())?"":req.getRobotContent());
                notice.setParamValue(GssBusinessNoticeConstant.TEMPLATE_SWITCH_ON);
                handleAiCallParam(req, spId);
            }else{
                aicallTaskService.updateAicallTask(req.getParamCode(), spId);
                aicallTask.setAppKey("");
                aicallTask.setAppSecret("");
                aicallTask.setRobotId("");
                aicallTask.setLineNum("");
                aicallTask.setRobotContent("");
                notice.setParamValue(GssBusinessNoticeConstant.TEMPLATE_SWITCH_OFF);
            }
        } else if (isDeviceOfflineAutomation(req.getParamCode())) {
            if (req.getSetRange() <= 0) {
                throw new BizException("请选择一种设置范围");
            }
            // 不同的范围进行走不同逻辑
            if (req.getSetRange() == 1) {
                notice.setSetRange("1");
                if (StringUtils.isEmpty(req.getPeriod()) || Integer.parseInt(req.getPeriod()) <= 0) {
                    throw new BizException("周期设置必须大于0");
                }else {
                    notice.setPeriod(req.getPeriod());
                }
                notice.setIsNotice(req.getIsNotice() ? 1 : 0); //离线情况是否通知 true-1、false-0
                notice.setEquipmentManufacturer("");
                notice.setEquipmentModel("");
                notice.setEquipmentType("");
            } else if (req.getSetRange() == 2) {
                notice.setSetRange("2");
                notice.setIsNotice(req.getIsNotice() ? 1 : 0); //离线情况是否通知 true-1、false-0
                if (!CollectionUtils.isEmpty(req.getEquipmentPeriod())) {
                    StringBuilder period = new StringBuilder();
                    StringBuilder equipmentType = new StringBuilder();
                    for (int i = 0; i < req.getEquipmentPeriod().size(); i++) {
                        if (i != 0) {
                            period.append(";");
                            equipmentType.append(";");
                        }
                        if (StringUtils.isEmpty(req.getEquipmentPeriod().get(i).getPeriod()) || Integer.parseInt(req.getEquipmentPeriod().get(i).getPeriod()) <= 0) {
                            throw new BizException("周期设置必须大于0");
                        }else {
                            period.append(req.getEquipmentPeriod().get(i).getPeriod());
                        }
                        equipmentType.append(req.getEquipmentPeriod().get(i).getEquipmentType());
                    }
                    notice.setPeriod(period.toString());
                    notice.setEquipmentType(equipmentType.toString());
                    notice.setEquipmentManufacturer("");
                    notice.setEquipmentModel("");
                }
            } else {
                notice.setSetRange("3");
                notice.setIsNotice(req.getIsNotice() ? 1 : 0); //离线情况是否通知 true-1、false-0
                if (!CollectionUtils.isEmpty(req.getEquipmentPeriod())) {
                    StringBuilder period = new StringBuilder();
                    StringBuilder equipmentManufacturer = new StringBuilder();
                    StringBuilder equipmentModel = new StringBuilder();
                    for (int i = 0; i < req.getEquipmentPeriod().size(); i++) {
                        System.out.println(req.getEquipmentPeriod().get(i).toString());
                        if (i != 0) {
                            period.append(";");
                            equipmentManufacturer.append(";");
                            equipmentModel.append(";");
                        }
                        if (StringUtils.isEmpty(req.getEquipmentPeriod().get(i).getPeriod()) || Integer.parseInt(req.getEquipmentPeriod().get(i).getPeriod()) <= 0) {
                            throw new BizException("周期设置必须大于0");
                        }else {
                            period.append(req.getEquipmentPeriod().get(i).getPeriod());
                        }
                        equipmentManufacturer.append(req.getEquipmentPeriod().get(i).getEquipmentManufacturer());
                        equipmentModel.append(req.getEquipmentPeriod().get(i).getEquipmentModel());
                    }
                    notice.setPeriod(period.toString());
                    notice.setEquipmentManufacturer(equipmentManufacturer.toString());
                    notice.setEquipmentModel(equipmentModel.toString());
                    notice.setEquipmentType("");
                }
            }
        }
        if (isSystemPopPresentationFormat(req.getParamCode())){
            notice.setPopMinutes(req.getPopMinutes());
            notice.setPopSeconds(req.getPopSeconds());
        } else{
            //pop_seconds默认为10,兼容非system_pop_presentation_format编辑时的情况
            notice.setPopSeconds(businessNotice.getPopSeconds());
        }
        if (isSystemUntreated(req.getParamCode())) {
            if (StringUtils.isEmpty(req.getParamValue())) {//参数值没设置
                throw new BizException("参数值不能为空！");
            }
            if ("OFF".equals(req.getParamValue())) {
                if (StringUtils.isEmpty(req.getSetRadius())) {
                    throw new BizException("请选择一种设置范围");
                }
                Integer popMinutes = req.getPopMinutes();
                if (popMinutes == null) {
                    popMinutes = 0;
                }
                Integer popSeconds = req.getPopSeconds();
                if (popSeconds == null) {
                    popSeconds = 0;
                }
                if (popMinutes <= 0 && popSeconds <= 0) {
                    throw new BizException("请选择一种自动时间");
                }
                if (popSeconds <= 0 && popMinutes > 0 && popMinutes <= 5) {
                    throw new BizException("需要有最小值，如5");
                }
            }
            if ("ON".equals(req.getParamValue())) {
                if (StringUtils.isEmpty(req.getSetRadius())) {
                    throw new BizException("请选择一种设置范围");
                }
            }
            notice.setSetRange(req.getSetRadius());
            notice.setPopMinutes(req.getPopMinutes());
            notice.setPopSeconds(req.getPopSeconds());
        }
        log.info("编辑业务通知：" + notice.toString());
        this.updateById(notice);

        //企业级操作日志
        Map<String, String> hashMap = EquipmentManufacturerMap();
        LogVO vo2 = new LogVO();
        vo2 = formatLog(vo2, template, req.getParamValue());
        if (isIgnoreParamValue(req.getParamCode())) {
            notice.setParamValue(null);
            businessNotice.setParamValue(null);
        }
        // 特殊处理字段
        if (isDeviceOfflineAutomation(req.getParamCode())){
            if (notice.getSetRange().equals("1")){
                notice.setSetRange("所有设备");
            }else if (notice.getSetRange().equals("2")){
                notice.setSetRange("设备类型");
            }else if (notice.getSetRange().equals("3")){
                notice.setSetRange("设备型号");
            }
            if (!StringUtils.isEmpty(notice.getEquipmentType())){
                if (notice.getEquipmentType().contains(";")){
                    List<String> split = Arrays.asList(notice.getEquipmentType().split(";"));
                    StringBuilder equipmentType = new StringBuilder();
                    for (int i = 0; i < split.size(); i++) {
                        if (i != 0) {
                            equipmentType.append(";");
                        }
                        equipmentType.append(EquipmentType.parse(split.get(i)).getName());
                    }
                    notice.setEquipmentType(equipmentType.toString());
                }else {
                    notice.setEquipmentType(EquipmentType.parse(notice.getEquipmentType()).getName());
                }
            }
            if (!StringUtils.isEmpty(notice.getEquipmentManufacturer()) ){
                if (notice.getEquipmentManufacturer().contains(";")){
                    List<String> split = Arrays.asList(notice.getEquipmentManufacturer().split(";"));
                    StringBuilder equipmentManufacturer = new StringBuilder();
                    for (int i = 0; i < split.size(); i++) {
                        if (i != 0) {
                            equipmentManufacturer.append(";");
                        }
                        equipmentManufacturer.append(hashMap.get(split.get(i)));
                    }
                    notice.setEquipmentManufacturer(equipmentManufacturer.toString());
                }else {
                    notice.setEquipmentManufacturer(hashMap.get(notice.getEquipmentManufacturer()));
                }
            }
        }
        if (isSystemPopPresentationFormat(req.getParamCode())){
            if (req.getParamValue().equals("OFF")){
                notice.setParamValue("自动关闭");
            }else {
                notice.setParamValue("手动关闭");
            }
            if (businessNotice.getParamValue().equals("OFF")){
                businessNotice.setParamValue("自动关闭");
            }else {
                businessNotice.setParamValue("手动关闭");
            }
        }
        if (isSystemUntreated(req.getParamCode())){
            if (req.getParamValue().equals("OFF")){
                notice.setParamValue("自动关闭");
            }else if (req.getParamValue().equals("ON")){
                notice.setParamValue("手动关闭");
            } else {
                notice.setParamValue("不提醒");
            }
            String setRange = req.getSetRadius();
            String[] split = setRange.split(",");
            StringBuilder sb = new StringBuilder();
            for (String rane : split) {
                if (rane.equals("1")) {
                    sb.append("报警记录未处理提醒,");
                }else if (rane.equals("2")){
                    sb.append("故障记录未处理提醒,");
                }
            }
            if (sb.length() > 0) {
                notice.setSetRange(sb.toString().substring(0, sb.length() - 1));
            } else {
                notice.setSetRange("");
            }

            if (!StringUtils.isEmpty(businessNotice.getParamValue())) {
                if (businessNotice.getParamValue().equals("OFF")){
                    businessNotice.setParamValue("自动关闭");
                }else if (businessNotice.getParamValue().equals("ON")){
                    businessNotice.setParamValue("手动关闭");
                } else {
                    businessNotice.setParamValue("不提醒");
                }
            } else {
                businessNotice.setParamValue("");
            }
            String setRanges = businessNotice.getSetRange();
            if (!StringUtils.isEmpty(setRanges)) {
                String[] splits = setRanges.split(",");
                StringBuilder sbs = new StringBuilder();
                for (String rane : splits) {
                    if (rane.equals("1")) {
                        sbs.append("报警记录未处理提醒,");
                    }else if (rane.equals("2")){
                        sbs.append("故障记录未处理提醒,");
                    }
                }
                if (sbs.length() > 0) {
                    businessNotice.setSetRange(sbs.toString().substring(0, sbs.length() - 1));
                }
            } else {
                businessNotice.setSetRange("");
            }
        }
        log.info("notice:{}",notice);
        String log1 = LogUtil.compareEntity(notice, businessNotice, BusinessNotice.class);
        vo2.setDetail(vo2.getDetail() + "成功 \n" +
                log1 + (StringUtils.isEmpty(log1) ? "" : "\n") +
                LogUtil.compareEntity(aicallTask, oldAicallTask, AicallTask.class));
        vo2.setCommonInfo(businessNotice.getParamName());
        LogRecordAspect.threadLocal.set(vo2);
    }

    /**
     *
     * 获取外呼信息
     *
     * @param spId
     * @param paramCode
     * @return
     */
    private AicallTask getOldAiCallTask(String spId,String paramCode){
        LambdaQueryWrapper<AicallTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AicallTask::getSpId,spId)
                .eq(AicallTask::getIsDeleted,0)
                .eq(AicallTask::getParamCode,paramCode)
                .orderByDesc(AicallTask::getCreatedAt);
        List<AicallTask> aicallTasks = aicallTaskService.getBaseMapper().selectList(queryWrapper);
        AicallTask aicallTask = null;
        if( ObjectUtils.isEmpty(aicallTasks) || aicallTasks.get(0).getTaskCode().contains("_yantai")){
            aicallTask = new AicallTask();
            aicallTask.setAppKey("");
            aicallTask.setAppSecret("");
            aicallTask.setRobotId("");
            aicallTask.setLineNum("");
            aicallTask.setRobotContent("");
        }else{
            aicallTask = aicallTasks.get(0);
        }
        aicallTask.setParamCode("");
        aicallTask.setOrgCode("");
        aicallTask.setAppId(0);
        aicallTask.setTaskCode("");
        aicallTask.setTaskName("");
        aicallTask.setTaskpoolId(0);
        aicallTask.setVoiceCode("");
        return aicallTask;
    }

    @Override
    public void del(Integer id) {
        BusinessNotice notice = new BusinessNotice();
        notice.setId(id);
        notice.setIsDeleted(true);
        log.info("删除业务通知：" + notice.toString());
        this.updateById(notice);
    }

    @Override
    public Map<String, Object> isSend(BrowserNotifyReason reason, String spId) {
        log.info("匹配业务通知规则 start");
        Map<String, Object> result = new HashMap<>();
        result.put("system", false);
        result.put("pop", false);

        Map<String,Object> qMap = new HashMap<>();
        qMap.put("spId", spId);
        List<BusinessNotice> list = this.selectParamList(qMap);

        if (list == null || list.isEmpty()) return result;
        switch (reason) {
            case Alert:
                result.put("notifyName", "设备报警");
                List<BusinessNotice> systemAlertList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.SYSTEM_ALERT_NOTICE.getCode())).collect(Collectors.toList());
                if (systemAlertList != null && systemAlertList.size() > 0) {
                    BusinessNotice system = systemAlertList.get(0);
                    if (system.getParamValue().equals("ON")) {
                        result.put("system", true);
                    }
                }
                List<BusinessNotice> popAlertList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.POP_ALERT_NOTICE.getCode())).collect(Collectors.toList());
                if (popAlertList != null && popAlertList.size() > 0) {
                    BusinessNotice pop = popAlertList.get(0);
                    if (pop.getParamValue().equals("ON")) {
                        result.put("pop", true);
                    }
                }
                break;
            case AlertRecover:
                result.put("notifyName", "报警恢复");
                List<BusinessNotice> systemAlertRecoverList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.SYSTEM_ALERT_RECOVERY_NOTICE.getCode())).collect(Collectors.toList());
                if (systemAlertRecoverList != null && systemAlertRecoverList.size() > 0) {
                    BusinessNotice system = systemAlertRecoverList.get(0);
                    if (system.getParamValue().equals("ON")) {
                        result.put("system", true);
                    }
                }
                List<BusinessNotice> popAlertRecoverList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.POP_ALERT_RECOVERY_NOTICE.getCode())).collect(Collectors.toList());
                if (popAlertRecoverList != null && popAlertRecoverList.size() > 0) {
                    BusinessNotice popAlert = popAlertRecoverList.get(0);
                    if (popAlert.getParamValue().equals("ON")) {
                        result.put("pop", true);
                    }
                }
                break;
            case ManualAlertRecover:
                result.put("notifyName", "手动报警恢复");
                List<BusinessNotice> systemManualAlertRecoverList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.SYSTEM_ALERT_RECOVERY_NOTICE.getCode())).collect(Collectors.toList());
                if (systemManualAlertRecoverList != null && systemManualAlertRecoverList.size() > 0) {
                    BusinessNotice system = systemManualAlertRecoverList.get(0);
                    if (system.getParamValue().equals("ON")) {
                        result.put("system", true);
                    }
                }
                List<BusinessNotice> popManualAlertRecoverList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.POP_ALERT_RECOVERY_NOTICE.getCode())).collect(Collectors.toList());
                if (popManualAlertRecoverList != null && popManualAlertRecoverList.size() > 0) {
                    BusinessNotice popAlert = popManualAlertRecoverList.get(0);
                    if (popAlert.getParamValue().equals("ON")) {
                        result.put("pop", true);
                    }
                }
                break;
            case Broken:
                result.put("notifyName", "设备故障");
                List<BusinessNotice> systemBrokenList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.SYSTEM_BROKEN_NOTICE.getCode())).collect(Collectors.toList());
                if (systemBrokenList != null && systemBrokenList.size() > 0) {
                    BusinessNotice system = systemBrokenList.get(0);
                    if (system.getParamValue().equals("ON")) {
                        result.put("system", true);
                    }
                }
                List<BusinessNotice> popBrokenList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.POP_BROKEN_NOTICE.getCode())).collect(Collectors.toList());
                if (popBrokenList != null && popBrokenList.size() > 0) {
                    BusinessNotice pop = popBrokenList.get(0);
                    if (pop.getParamValue().equals("ON")) {
                        result.put("pop", true);
                    }
                }
                break;
            case BrokenRecover:
                result.put("notifyName", "故障恢复");
                List<BusinessNotice> systemBrokenRecoverList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.SYSTEM_BROKEN_RECOVERY_NOTICE.getCode())).collect(Collectors.toList());
                if (systemBrokenRecoverList != null && systemBrokenRecoverList.size() > 0) {
                    BusinessNotice system = systemBrokenRecoverList.get(0);
                    if (system.getParamValue().equals("ON")) {
                        result.put("system", true);
                    }
                }
                List<BusinessNotice> popBrokenRecoverList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.POP_BROKEN_RECOVERY_NOTICE.getCode())).collect(Collectors.toList());
                if (popBrokenRecoverList != null && popBrokenRecoverList.size() > 0) {
                    BusinessNotice pop = popBrokenRecoverList.get(0);
                    if (pop.getParamValue().equals("ON")) {
                        result.put("pop", true);
                    }
                }
                break;
            case ManualBrokenRecover:
                result.put("notifyName", "手动故障恢复");
                List<BusinessNotice> systemManualBrokenRecoverList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.SYSTEM_BROKEN_RECOVERY_NOTICE.getCode())).collect(Collectors.toList());
                if (systemManualBrokenRecoverList != null && systemManualBrokenRecoverList.size() > 0) {
                    BusinessNotice system = systemManualBrokenRecoverList.get(0);
                    if (system.getParamValue().equals("ON")) {
                        result.put("system", true);
                    }
                }
                List<BusinessNotice> popManualBrokenRecoverList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.POP_BROKEN_RECOVERY_NOTICE.getCode())).collect(Collectors.toList());
                if (popManualBrokenRecoverList != null && popManualBrokenRecoverList.size() > 0) {
                    BusinessNotice pop = popManualBrokenRecoverList.get(0);
                    if (pop.getParamValue().equals("ON")) {
                        result.put("pop", true);
                    }
                }
                break;
            case PowerOff:
                result.put("notifyName", "设备关机");
                List<BusinessNotice> systemPowerOffList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.SYSTEM_OFFLINE_NOTICE.getCode())).collect(Collectors.toList());
                if (systemPowerOffList != null && systemPowerOffList.size() > 0) {
                    BusinessNotice system = systemPowerOffList.get(0);
                    if (system.getParamValue().equals("ON")) {
                        result.put("system", true);
                    }
                }
                List<BusinessNotice> popPowerOffList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.POP_OFFLINE_NOTICE.getCode())).collect(Collectors.toList());
                if (popPowerOffList != null && popPowerOffList.size() > 0) {
                    BusinessNotice pop = popPowerOffList.get(0);
                    if (pop.getParamValue().equals("ON")) {
                        result.put("pop", true);
                    }
                }
                break;
            case ManualPowerOff:
                result.put("notifyName", "手动设备关机");
                List<BusinessNotice> systemManualPowerOffList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.SYSTEM_OFFLINE_NOTICE.getCode())).collect(Collectors.toList());
                if (systemManualPowerOffList != null && systemManualPowerOffList.size() > 0) {
                    BusinessNotice system = systemManualPowerOffList.get(0);
                    if (system.getParamValue().equals("ON")) {
                        result.put("system", true);
                    }
                }
                List<BusinessNotice> popManualPowerOffList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.POP_OFFLINE_NOTICE.getCode())).collect(Collectors.toList());
                if (popManualPowerOffList != null && popManualPowerOffList.size() > 0) {
                    BusinessNotice pop = popManualPowerOffList.get(0);
                    if (pop.getParamValue().equals("ON")) {
                        result.put("pop", true);
                    }
                }
                break;
            case DeviceCycOff:
                result.put("notifyName", "设备离线(通讯不成功)");
                List<BusinessNotice> systemDeviceCycOffList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.SYSTEM_OFFLINE_NOTICE.getCode())).collect(Collectors.toList());
                if (systemDeviceCycOffList != null && systemDeviceCycOffList.size() > 0) {
                    BusinessNotice system = systemDeviceCycOffList.get(0);
                    if (system.getParamValue().equals("ON")) {
                        result.put("system", true);
                    }
                }
                List<BusinessNotice> popDeviceCycOffList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.POP_OFFLINE_NOTICE.getCode())).collect(Collectors.toList());
                if (popDeviceCycOffList != null && popDeviceCycOffList.size() > 0) {
                    BusinessNotice pop = popDeviceCycOffList.get(0);
                    if (pop.getParamValue().equals("ON")) {
                        result.put("pop", true);
                    }
                }
                break;
            case PowerOn:
                result.put("notifyName", "设备开机");
                List<BusinessNotice> systemPowerOnList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.SYSTEM_ONLINE_NOTICE.getCode())).collect(Collectors.toList());
                if (systemPowerOnList != null && systemPowerOnList.size() > 0) {
                    BusinessNotice system = systemPowerOnList.get(0);
                    if (system.getParamValue().equals("ON")) {
                        result.put("system", true);
                    }
                }
                List<BusinessNotice> popPowerOnList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.POP_ONLINE_NOTICE.getCode())).collect(Collectors.toList());
                if (popPowerOnList != null && popPowerOnList.size() > 0) {
                    BusinessNotice pop = popPowerOnList.get(0);
                    if (pop.getParamValue().equals("ON")) {
                        result.put("pop", true);
                    }
                }
                break;
            case ManualPowerOn:
                result.put("notifyName", "手动设备开机");
                List<BusinessNotice> systemManualPowerOnList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.SYSTEM_ONLINE_NOTICE.getCode())).collect(Collectors.toList());
                if (systemManualPowerOnList != null && systemManualPowerOnList.size() > 0) {
                    BusinessNotice system = systemManualPowerOnList.get(0);
                    if (system.getParamValue().equals("ON")) {
                        result.put("system", true);
                    }
                }
                List<BusinessNotice> popManualPowerOnList = list.stream().filter(a -> a.getParamCode().equals(BusinessNoticeParam.POP_ONLINE_NOTICE.getCode())).collect(Collectors.toList());
                if (popManualPowerOnList != null && popManualPowerOnList.size() > 0) {
                    BusinessNotice pop = popManualPowerOnList.get(0);
                    if (pop.getParamValue().equals("ON")) {
                        result.put("pop", true);
                    }
                }
                break;
            default:
                break;
        }
        log.info(result.toString());
        log.info("匹配业务通知规则 end");
        return result;
    }


    /**
     * 复制消息配置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void duplicateNotices(String spId) {
        log.info("企业消息数据复制。。");

        BusinessNotice notice = new BusinessNotice();
        for (BusinessNoticeParam param : BusinessNoticeParam.values()) {
            // 热线电话不添加
            if (BusinessNoticeParam.CM_SERVICE_HOT_LINE.equals(param)) {
                continue;
            }

            QueryWrapper<BusinessNotice> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(BusinessNotice::getSpId, spId)
                    .eq(BusinessNotice::getIsDeleted, YesNoEnum.N.getCode())
                    .eq(BusinessNotice::getParamCode, param.getCode());
            int count = this.count(queryWrapper);
            // 已存在的不添加
            if (count > 0) {
                continue;
            }

            // 不存在的再添加
            notice.setSpId(spId);
            notice.setParamName(param.getName());
            notice.setParamCode(param.getCode());
            notice.setParamValue("ON");
            notice.setRemark(param.getRemark());
            this.save(notice);
        }
        log.info("企业消息数据复制完成。");
    }

    @Override
    public BusinessNotice getByCode(String code, String spId) {
        LambdaQueryWrapper<BusinessNotice> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BusinessNotice::getParamCode, code).eq(BusinessNotice::getSpId, spId).eq(BusinessNotice::getIsDeleted, Constants.IS_DELETED_FALSE);
        List<BusinessNotice> list = this.list(lqw);
        if (!CollectionUtils.isEmpty(list)){
            return list.get(0);
        }
        return null;

    }

    @Override
    public Boolean switchValueByCode(String code, String spId) {
        BusinessNotice businessNotice = this.getByCode(code, spId);
        if (null == businessNotice) {
            return false;
        }else
            return "ON".equals(businessNotice.getParamValue());
    }

    @Override
    public List<BusinessNotice> selectParamList(Map<String, Object> params) {
        return this.baseMapper.selectParamList(params);
    }

    public Map<String,String> EquipmentManufacturerMap(){
        return equipmentManufacturerService.queryNameMap();
    }

    @Override
    public List<BusinessNotice> selectParamCode(String paramCode) {
        return this.baseMapper.selectParamCode(paramCode);
    }


    /**
     * 获取服务套餐错误
     * @param spId
     * @return
     */
    @Override
    public Boolean getServicePackageSwitch(String spId){
        String diffServicePackageMode = "OFF";
        try {
            BusinessNotice businessNotice = this.getByCode(BusinessNoticeParam.DIFFERENT_SERVICE_PACKAGE_MODE.getCode(), spId);
            if (!ObjectUtils.isEmpty(businessNotice)) {
                diffServicePackageMode = businessNotice.getParamValue();
            }
        }catch (Exception e){
            log.error("getServicePackageSwitch error",e);
        }
        return diffServicePackageMode.equalsIgnoreCase("ON");
    }

}
